from rest_framework.viewsets import ModelViewSet, GenericViewSet
from rest_framework import mixins
from rest_framework.response import Response
from live.models import Channel
from live.serializers import ChannelSerializer
from xmanage.response import LIVE_NAME_VALIED, SYS_ERROR, API_SUCCESS
from libs.utils.polyv import createLive
import time


# Create your views here.
class LiveView(ModelViewSet):
     queryset = Channel.objects.order_by('-ctime').all()
     serializer_class = ChannelSerializer

     def create(self, request, *args, **kwargs):
          user_id = 1
          name = request.POST['name']
          channel_passwd = request.POST['channel_passwd']
          scene = 'ppt'
          max_viewer = int(request.POST['max_viewer'])
          publisher = request.POST['publisher']
          publisher_duty = request.POST['publisher_duty']
          start_time = request.POST['start_time']
          be_email = request.POST['be_email']

          if name == '':
               return Response(LIVE_NAME_VALIED)

          try:
               liveInfo = createLive(name, channel_passwd, scene, max_viewer, start_time, publisher)

               live_body = {
                    "name": name,
                    "live_user_id": liveInfo.get("userId"),
                    "stream": liveInfo.get("stream"),
                    "url": liveInfo.get("m3u8Url"),
                    "channel_number": liveInfo.get("channelId")
                    "channel_passwd": channel_passwd,
                    "scene": scene,
                    "max_viewer": max_viewer,
                    "start_time": start_time,
                    "publisher": publisher,
                    "publisher_duty": publisher_duty,
                    "create_user_id": user_id,
                    "be_email": be_email,
                    "ctime": time.time()
               }

               serializer = self.serializer_class(data=live_body)
               #self.serializer_class.create(**live_body)
               if serializer.is_valid():
                    serializer.save()
                    return Response(API_SUCCESS)

               return Response(SYS_ERROR)
          except Exception:
               return Response(SYS_ERROR)



